package ch.usi.inf.pf2.gui.chart;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JComponent;

import ch.usi.inf.pf2.cell.*;
import ch.usi.inf.pf2.gui.JSpreadSheetGUI;

/**
 * 
 * @author Lorenzo Baracchi <lorenzo.baracchi@usi.ch>
 *
 */
public class BarChart extends JComponent
{
	JSpreadSheetGUI spreadTable; 
	int[][] selectedCells;
	int number;
	final int MAX_HEIGTH = 300;
	final int WIN_HEIGTH;


	/**
	 * Create the bar chart.
	 * @param spreadTable The table to which the built bar-chart is related to
	 * @param selectedRows The rows of the selected cells
	 * @param selectedColumns The columns of the selected cells
	 * @param winHeigth The size of the chart window
	 */
	public BarChart (JSpreadSheetGUI spreadTable, int[] selectedRows, int[] selectedColumns, int winHeigth)
	{
		this.spreadTable=spreadTable;
		selectedCells= new int[selectedRows.length][selectedColumns.length];
		number=selectedRows.length*selectedColumns.length;
		for(int i=0; i<selectedRows.length; i++) {
			for(int j=0; j<selectedColumns.length; j++) {
				Data cellData = spreadTable.getSheet().getCell(selectedColumns[j]+1, selectedRows[i]+1).getContent();
				if (cellData instanceof Formula) {
					selectedCells[i][j]  = (int)Double.parseDouble(((Formula)cellData).getActualValue());
				} else if (cellData instanceof Text) {

				} else {
					selectedCells[i][j]=(int)Double.parseDouble(spreadTable.getSheet().getCell(selectedColumns[j]+1, selectedRows[i]+1).getContent().toString());
				}
			}
		}
		WIN_HEIGTH=winHeigth-20;
	}


	/**
	 * @return The greatest value in the array.
	 */
	public int maxArray ()
	{
		int max = Integer.MIN_VALUE;
		for(int i=0; i<selectedCells.length; i++)
			for(int j=0; j<selectedCells[i].length; j++)
				if(selectedCells[i][j]>max)
					max=selectedCells[i][j];
		return max;
	}


	/**
	 * @return a suitable width of the window fitting with
	 * the number of bars in the chart
	 */
	public int width ()
	{
		return 30*number+15;
	}


	/**
	 * Draw the chart.
	 */
	public void paint (Graphics g)
	{
		int max = maxArray();
		int p=0;
		for(int i=0; i<selectedCells.length; i++)
			for(int j=0; j<selectedCells[i].length; j++)
			{
				int h = (int) (((double)(selectedCells[i][j])/(double)(max))*(double)(MAX_HEIGTH));
				g.setColor(ChartColor.selectColor(p+1));
				g.drawRect(p*30+10, WIN_HEIGTH-h-20, 15, h);
				g.fillRect(p*30+10, WIN_HEIGTH-h-20, 15, h);
				g.setColor(Color.black);
				g.drawString(selectedCells[i][j]+"", p*30+10, WIN_HEIGTH-h-5-20);
				g.drawString(getCellReference(j,i), p*30+10, WIN_HEIGTH-5);
				p++;
			}
	}

	private String getCellReference(int row, int col) {
		int r = spreadTable.getSelectedColumns()[row]+1;
		int c = spreadTable.getSelectedRows()[col]+1;
		Converter conv = new Converter();
		conv.setCellReferenceNumbers(new int[]{r,c});
		conv.convertToString();
		return conv.getCellReference();
	}
}
